package com.lesso.zgs.sunflower.core.sharding;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collection;
import java.util.Date;

/**
 * YearPreciseShardingAlgorithm
 * 按年份分表的精确分片算法
 */
public class YearPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Date> {
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Date> shardingValue) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(
                Instant.ofEpochMilli(shardingValue.getValue().getTime()), ZoneId.systemDefault());
        int year = localDateTime.getYear();
        String targetTableName = "base_employee_" + year;
        for (String tableName : availableTargetNames) {
            if (tableName.equals(targetTableName)) {
                return tableName;
            }
        }
        throw new IllegalArgumentException("找不到年份 " + year + " 对应的分表: " + targetTableName);
    }
} 